<?php
namespace Weixin\Controller;
use Think\Controller;
use Home\Controller\CommonController;
class PayController extends Controller {
	
    
    public function index(){
    	
    	//$openid = $_SESSION['_loginUser_home']['openid'];
    	$id = I('id');
    	if(!$id){
    		echo 'id错误';
    		exit();
    	}

    	$this->info = D('YgclOrder')->where(array('id'=>$id))->relation(true)->find();
    	if($this->info['type'] == 'tiyan'){
    		$this->tiyan = D('YgclTiyan')->where(array('id'=>$this->info['objectid']))->find();
    	}
    	if($this->info['type'] == 'qitatiyan'){
    		$this->qitatiyan = D('YgclQitatiyan')->where(array('id'=>$this->info['objectid']))->find();
    	}
    	
    	//取openid
    	$uid = $this->info['uid'];
		$openid = M('Users')->where(array('uid'=>$uid))->getField('openid');
		if(!$openid){
			echo 'openid为空，错误';
			exit();
		}
    	
    	//订单参数
    	$ddbh = $this->info['ddbh'];
    	$total_fee = $this->info['total'];
    	$notify_url = 'http://ygcl.sunny-art.cn/weixin/pay/notify.html';
    	
    	$type = $this->info['type'];
    	if($type === 'baoming'){
    		$tpl = 'index';
    		$body = '课程报名/'.$this->info['ddbh']."/".$this->info['stuname']."/".$this->info['tel']."/金额：".$this->info['total'];
    	}elseif($type === 'midbm'){
    		$tpl = 'index';
    		$body = '课程中途报名/'.$this->info['ddbh']."/".$this->info['stuname']."/".$this->info['tel']."/金额：".$this->info['total'];
    	}elseif ($type === 'freepay'){
    		$tpl = 'freepay';
    		$body = '自定义支付/金额：'.$this->info['total'];
    	}elseif($type === 'tiyan'){
    		$tpl = 'tiyanpay';
    		$body = '体验课/金额：'.$this->info['total'];
    	}elseif ($type === 'qitatiyan'){
    		$tpl = 'qttiyanpay';
    		$body = '其他体验课/金额：'.$this->info['total'];
    	}elseif($type === 'dashang'){
    		$tpl = 'dashang';
    		$teacherid = D('YgclTeacherContents')->where(array("id"=>$this->info['objectid']))->getField('creator_id');
    		$teacherinfo['teacher'] = D('Users')->where(array('uid'=>$teacherid))->relation(true)->find();
    		$teacherinfo['kecheng'] = R('Home/Fuwu/getkecheng',array($teacherid,$this->info['did']));
    		$teacherinfo['id'] = $teacherid;
    		$this->teacherinfo= $teacherinfo;
    		$body = '打赏/'.$teacherinfo['teacher']['realname'].'/金额：'.$this->info['total'].'/时间：'.$this->info['create_time'];
    	}elseif($type === 'kjbm'){
    		$tpl = 'kjbm';
    		$body = '考级报名/'.$this->info['xiaoqu']['title'].'/金额：'.$this->info['total'];
    	}elseif($type === 'summer2018'){
    		$tpl = 'summer';
    		$body = '2018暑期班报名/'.$this->info['stuname'].'/'.$this->info['xiaoqu']['title'].'/金额：'.$this->info['total'];
    	}
    	if(strlen($body)>127){
    		echo 'body参数长度有误';
    		exit();
    	}
    	if($this->info['status'] == 2){
    		$jsApiParameters = $this->getConfig($openid,$ddbh,$body,$total_fee,$notify_url);
    		$this->jsApiParameters = $jsApiParameters;
    	}
    	$this->display($tpl);
    }
    
    public function notify(){
        Vendor('Wxpay.WxPay#Api');
        $raw_xml = file_get_contents("php://input");
        $notify = new \WxPayNotifyCallBack();
        $notify->Handle(false);
        $res = $notify->GetValues();
        if($res['return_code'] ==="SUCCESS" && $res['return_msg'] ==="OK"){
            libxml_disable_entity_loader(true);
            $ret = json_decode(json_encode(simplexml_load_string($raw_xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
            \Think\Log::write('微信JSAPI/APP支付成功订单号'.$ret['out_trade_no'], \Think\Log::DEBUG);
            //在此处处理业务逻辑部分
            //D('PayNotify','Service')->update_order($ret);
            $m = M('YgclOrder');
            $where['ddbh'] = $ret['out_trade_no'];
            $where['status'] = 2;
            $info = $m->where($where)->find();
            //更新订单的状态
            if($info){
            	$orderdate = array(
            		'id'=>$info['id'],
            		'status' => 1,//已支付
            		'wxddh' => $ret['transaction_id'],
            		'pay_time' => Date('Y-m-d H:i:s')
            	);
            	if($m->save($orderdate)){
            		//报名课程信息更新
            		if($info['type'] == 'baoming'){
            			//积分增加
            			M('Users')->where(array('uid'=>$info['uid']))->setInc('score',ceil($ret['total_fee']/100));
            			A('Home/LessonStudentRelation')->_add_lesson_student_relation($info['id']);
            		}
            		 
            		if($info['type'] == 'midbm'){
            			A('Home/LessonStudentRelation')->_add_midbm_info($info['id']);
            		}
            	}
            	
            	
            	\Think\Log::write($ret['out_trade_no'].'更新成功', \Think\Log::DEBUG);
            }else{
            	\Think\Log::write($ret['out_trade_no'].'更新失败', \Think\Log::DEBUG);
            }

           
        }
    }
    
    public function getConfig($openid,$ddbh,$body,$total_fee,$notify_url){
    	header("Content-Type: text/html;charset=utf-8");
    	Vendor('Wxpay.WxPay#JsApiPay');
    	$tools = new \JsApiPay();
    	//$openId = $tools->GetOpenid();
    	$openId = $openid;
//     	if(!$openId){
//     		echo '请先登录';
//     		exit();
//     	}
    	//统一下单
    	//$body = "自定义支付金额：1";
    	 
    	$input = new \WxPayUnifiedOrder();
    	$input->SetBody($body);
    	$input->SetAttach($ddbh);
    	$input->SetOut_trade_no($ddbh);
    	$input->SetTotal_fee($total_fee*100);
    	$input->SetTime_start(date("YmdHis"));
    	$input->SetTime_expire(date("YmdHis", time() + 600));
    	$input->SetGoods_tag("test");
    	$input->SetNotify_url($notify_url);//支付回调地址，这里改成你自己的回调地址。
    	$input->SetTrade_type("JSAPI");
    	$input->SetOpenid($openId);
    	$order = \WxPayApi::unifiedOrder($input);
    	$jsApiParameters = $tools->GetJsApiParameters($order);
    	 
    	return $jsApiParameters;
//     	$data = array(
//     		'status' => 'ok',
//     		'wxconf' => $jsApiParameters,
//     	);
//     	$this->ajaxReturn($data);
    }
}